<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<%@ include file="/include/taglibs.jsp"%>
<title>用户管理</title>
<link rel="stylesheet" href="${ctx}/assets/admin/LingUI/css/jquery-ui.min.css" />
<link rel="stylesheet" href="${ctx}/assets/admin/LingUI/css/ui.jqgrid.css" />
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/ztree/js/jquery.ztree.core-3.5.js" ></script>		<!-- 树插件核心 -->
<script type="text/javascript" src="${ctx}/assets/admin/LingUI/js/ztree/js/jquery.ztree.exedit-3.5.js" ></script>		<!-- 树编辑插件 -->
<script type="text/javascript" src="${ctx}/assets/uc/js/common.js"></script>
<div class="row xtgltree">
	<input type="text" id="selectDepId" style="display:none"/>
	<div class="col-sm-3">
		<div class="widget-box widget-color-blue2" style="height:600px;min-height:420px; height:auto!important">
			<div class="widget-header">
				<h4 class="widget-title lighter smaller">部门列表</h4>
			</div>
			<div class="widget-body">
				<div class="widget-main padding-8">
					<div class="zTreeDemoBackground">
						<ul id="treeDemo" class="ztree"></ul>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="col-sm-9">
		<div class="widget-box " style="height:600px;min-height :420px; height:auto!important">
			<div class="widget-header">
				<h4 class="widget-title lighter smaller">用户列表</h4>
			</div>
			<div id="search" style="padding: 8px"></div>											<%--查询条件更多 --%>
			<div class="b_grid_line  col-lg-12"></div>
			<div class="widget-body">
				<div class="widget-main padding-8 admin-body">
					<table id="admin_table"></table>
					<div id="admin_pager"></div>
				</div>
			</div>
		</div>
	</div>

</div>

<script type="text/javascript">
	//导入脚本
	var scripts = [null,
		"${ctx}/assets/admin/LingUI/js/jqGrid/jquery.jqGrid.js",
		"${ctx}/assets/admin/LingUI/js/jqGrid/i18n/grid.locale-cn.js",
		"${ctx}/assets/admin/LingUI/js/control.js",
		"${ctx}/assets/admin/LingUI/js/jsutil/js/jquery.filterSearch.js",
		null];

	/**
	 * 设置全局变量
	 */
	var tree ="treeDemo";//树id
	var $tree=$("#treeDemo");
	var zTree; //树对象

	var _grid_id = "#admin_table";	//表格 选择器
	var _pager_id = "#admin_pager";	//表格页脚 选择器
	var url = "${ctx}/${frameworkPath}/user/index?sort=USER_ORDER&&dir=asc"; //表格url

	ace.load_ajax_scripts(scripts, function() {
		jQuery(function($){
			$('input, textarea').placeholder(); //空输入框中占位符
			var setting = {
				async:{
					autoParam: ["id=id"],
					enable:true,
					type:"GET",
					dataType:'json',
					url:"${ctx}/${frameworkPath}/org/children"
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onClick: onClick,				//树节点点击事件
					onAsyncSuccess: zTreeOnAsyncSuccess
				}
			};

			$("#search").strongFilterSearch({
				inputFiled:"USER_ID",				//搜索字段，不填默认为searchValue
				inputPlaceholder:"请输入用户帐号等关键字",		//占位符
				searchCallback : callback//,				//搜索按钮点击后回调
			});
			//搜索回调函数
			function callback(data){
				jQuery(_grid_id).jqGrid('setGridParam', {
					url : url,
					mtype : "POST",
					postData:data //传递的数据
				}).trigger("reloadGrid");
			}

			zTree=$.fn.zTree.init($tree, setting); //树初始化

			//调整以适应页面大小  其中 $(".page-content") 为jqgrid的父级容器
			$(window).off('resize.jqGrid').on('resize.jqGrid', function () {
				setTimeout(function(){
					$(_grid_id).jqGrid("setGridWidth",$(".admin-body").width());
					$(".ui-jqgrid-bdiv").width($(".admin-body").width()+1);
				},50);
			});

			jQuery(_grid_id).jqGrid({
				url: url,
				postData:{
					org:1//相当于不查询
				},
				colNames:['账号', '姓名', '邮箱' ,'邮编','状态','所属岗位','创建日期','操作'],
				colModel:[
					{name:'username',index:'username',key:true,width:30,hidden:false},
					{name:'name',index:'name',width:50},
					{name:'email',index:'email',width:80 ,align :'left'},
					{name:'post',index:'post',width:40 ,align :'left'},
					{name:'enabled',index:'enable',width:20 ,align :'center'
						,formatter : function(cellvalue,options,rowObject){
							if (cellvalue == true) {
								return "<span class='label  label-success'>启用</span>";
							} else {
								return "<span class='label  label'>禁用</span>";
							}
						}
					},
					{name:'positionname',index:'positionname',width:40 ,align :'left'},
					{name:'created',index:'created',width:50 ,align :'center'
						,formatter : function(cellvalue,options,rowObject){
						return lui.timestampFormat(cellvalue,"YYYY-MM-DD");
					}
					},
					{name:'myac',width:40,fixed:false,sortable:false,align:'center'
						, formatter: function(cellvalue, options, rowObject) {
						var s='<div class=" action-buttons">'
						<shiro:hasPermission name="USER_EDIT">
							s=s+  '<a class="blue" title="编辑" style="cursor:pointer" ><i class="ace-icon fa fa-pencil bigger-130 " onclick="editrows(\''+rowObject.id+'\')"></i></a>';
						</shiro:hasPermission>
						<shiro:hasPermission name="USER_DELETE">
							s=s+  '<a class="blue" title="删除" style="cursor:pointer" ><i class="ace-icon fa fa-trash-o red bigger-130 " onclick="editrows(\''+rowObject.id+'\')"></i></a>';
						</shiro:hasPermission>
						<shiro:hasPermission name="USER_ENABLE">
							s=s+  '<a class="blue" title="启用" style="cursor:pointer" ><i class="ace-icon fa fa-unlock green bigger-130 " onclick="editrows(\''+rowObject.id+'\')"></i></a>';
						</shiro:hasPermission>
						<shiro:hasPermission name="USER_DISABLE">
							s=s+  '<a class="blue" title="禁用" style="cursor:pointer" ><i class="ace-icon fa fa-lock red bigger-130 " onclick="editrows(\''+rowObject.id+'\')"></i></a>';
						</shiro:hasPermission>
						return s+'</div>';
					}
					}
				],
				pager : _pager_id //分页信息 放置的位置
			});
			//自定义工具栏 =============BEGIN======================//
			var jqgridButton=jQuery(_grid_id).jqGrid('navGrid',_pager_id);

			<shiro:hasPermission name="USER_CREATE">
			jqgridButton.navButtonAdd( _pager_id,{
				title : "新增",//按钮悬浮提示
				buttonicon : "ace-icon fa fa-plus-circle purple",//按钮图标和颜色
				onClickButton : addrows //点击按钮响应方法    
			})
			</shiro:hasPermission>

			<shiro:hasPermission name="USER_DELETE">
			jqgridButton.navButtonAdd( _pager_id,{
				title : "删除",
				buttonicon : "ace-icon fa fa-trash-o red",
				onClickButton : function(){
					var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
					if(idArr.length == 0){
						lui.info("请选择一条记录！")
						return;
					}
					else{
						var rowDataArr = $(_grid_id).jqGrid("getRowDataArr");//获取所有选中的row 的数据数组
						for(var i in rowDataArr){
							var rowData=rowDataArr[i];
							if(rowData["enabled"].indexOf("启用")!=-1){
								lui.info("账号["+rowData['username']+"]为有效客户不能被删除！");
								return;
							}
						}
						lui.confirm("确定删除所选记录吗？"
								,function(){
									deleteUsers(idArr);
								},function(){

								});
					}
				}
			})
			</shiro:hasPermission>

			jqgridButton.navButtonAdd( _pager_id,{
				title : "刷新",
				buttonicon : "ace-icon fa fa-refresh orange",
				onClickButton : function(){
					reloadGrid();
				}
			}).navSeparatorAdd() //分隔符

			<shiro:hasPermission name="USER_ENABLE">
			jqgridButton.navButtonAdd( _pager_id,{
				title : "启用",
				iconTitle : "启用",
				buttonicon : "ace-icon fa  fa-unlock green",
				onClickButton : function(){
					var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
					if(idArr.length == 0){
						lui.info("请选择一条记录！")
						return;
					}else{
						enableUser(idArr);
					}
				}
			})
			</shiro:hasPermission>
			<shiro:hasPermission name="USER_DISABLE">
			jqgridButton.navButtonAdd( _pager_id,{
				title : "禁用",
				iconTitle : "禁用",
				buttonicon : "ace-icon fa  fa-lock red",
				onClickButton : function(){
					var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
					if(idArr.length == 0){
						lui.info("请选择一条记录！")
						return;
					}
					else{
						disableUser(idArr);
					}
				}
			}).navSeparatorAdd() //分隔符
			</shiro:hasPermission>

			<shiro:hasPermission name="USER_ROLE">
			jqgridButton.navButtonAdd( _pager_id,{
				title : "分配角色",
				buttonicon : "ace-icon fa fa-users green",
				onClickButton : function(){
					var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
					if(idArr.length == 0){
						lui.info("请选择一条记录！")
						return;
					}
					else if(idArr.length >1){
						lui.info("最多选择一条记录！")
						return;
					}
					else{
						lui.open({
							title : "分配角色",
							content : '${ctx}/${frameworkPath}/user/role?username='+idArr[0],
							area : [ "60%" , "500px" ],
							yes: function(index, layero){
								var retObj = $(layero).find("iframe")[0].contentWindow.submit();
								if(retObj && retObj.text){
									lui.info(retObj.text);
									if(retObj.state){
										layer.close(index);
										reloadGrid({
											org : $("#selectDepId").val()
										});
									}
								}
							}
						});
					}
				}
			}).navSeparatorAdd()
			</shiro:hasPermission>
			jqgridButton.navButtonAdd( _pager_id,{
				title : "重置密码",
				buttonicon : "ace-icon fa fa-key",
				onClickButton : function(){
					var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
					if(idArr.length == 0){
						lui.info("请选择一条记录！")
						return;
					}
					else if(idArr.length >1){
						lui.info("最多选择一条记录！")
						return;
					}
					lui.confirm("确定要重置所选用户的密码吗？"
							,function(){
								resetPassword(idArr);
							},function(){

							});
				}
			})
		});
	});

	/**
	 * 表格刷新
	 */
	function reloadGrid(data){
		jQuery(_grid_id).jqGrid('setGridParam', {
			url : url,
			postData : data //传递的数据
		}).trigger("reloadGrid");
	}
	/**
	 * 新增用户
	 */
	function addrows(){
		lui.open({
			title : "添加用户",
			content : "${ctx}/${frameworkPath}/user/create?org=" + $("#selectDepId").val() ,
			area : [ "60%" , "500px" ],
			yes: function(index, layero){
				var retObj = $(layero).find("iframe")[0].contentWindow.formValid();
				if(retObj && retObj.text){
					lui.success(retObj.text);
					if(retObj.state){
						layer.close(index);
						reloadGrid({
							org : $("#selectDepId").val()
						});
					}
				}
			}
		});

		//toLocation("#sf/user/create")
	}

	/**
	 * 编辑
	 */
	function editrows(id){
		lui.open({
			title : "账号信息",
			content : "${base}/admin/user/edit.do?id=" + id ,
			area : [ "60%" , "500px" ],
			yes: function(index, layero){
				var retObj = $(layero).find("iframe")[0].contentWindow.formValid();
				if(retObj && retObj.text){
					lui.info(retObj.text);
					if(retObj.state == "success"){
						layer.close(index);
						reloadGrid({
							depId : $("#selectDepId").val()
						});
					}
				}
			}
		});
	}

	/**
	 * 表格删除
	 */
	function deleteUsers(ids){
		var selectDepId = $("#selectDepId").val();
		var idArray = new Array();
		for ( var i = 0; i < ids.length; i++) {
			idArray.push(ids[i]);
		}
		$.ajax({
			type : 'POST',
			url : '${ctx}/${frameworkPath}/user/delete',
			traditional : true,
			dataType:'json',
			data : {'usernames' : idArray,_method:'delete'},
			success : function(message) {
				if(message.success){
					lui.success('删除成功');
					reloadGrid({
						org : selectDepId
					});
				}
				else{
					lui.fail(message.error);
				}
			}
		});
	}

	function disableUser(ids){
		var selectDepId = $("#selectDepId").val();
		var idArray = new Array();
		for ( var i = 0; i < ids.length; i++) {
			idArray.push(ids[i]);
		}
		$.ajax({
			type : 'POST',
			url : '${ctx}/${frameworkPath}/user/disable',
			traditional : true,
			dataType:'json',
			data : {'usernames' : idArray},
			success : function(data) {
				if(data.success){
					lui.success("操作成功");
					reloadGrid({
						org : $("#selectDepId").val()
					});
				}
				else{
					lui.fail("操作失败");
				}
			},
			error : function(XmlHttpRequest, textStatus, errorThrown) {
				lui.fail("操作失败:"+XmlHttpRequest.status);
			}
		});
	}

	function enableUser(ids){
		var selectDepId = $("#selectDepId").val();
		var idArray = new Array();
		for ( var i = 0; i < ids.length; i++) {
			idArray.push(ids[i]);
		}
		$.ajax({
			type : 'POST',
			url : '${ctx}/${frameworkPath}/user/enable',
			traditional : true,
			dataType:'json',
			data : {'usernames' : idArray},
			success : function(data) {
				if(data.success){
					lui.success("操作成功");
					reloadGrid({
						org : $("#selectDepId").val()
					});
				}
				else{
					lui.fail("操作失败");
				}
			},
			error : function(XmlHttpRequest, textStatus, errorThrown) {
				lui.fail("操作失败:"+XmlHttpRequest.status);
			}
		});
	}

	/**
	 * 转移部门
	 */
	function transferDept(ids){
		lui.open({
			title : "转移部门",
			content : "${base}/admin/user/deptree.do",
			area : [ "400px" , "400px" ],
			yes: function(index, layero){
				var idArr = $(_grid_id).jqGrid("getGridParam", "selarrrow");//获取所有选中行的id字符串
				var dept = $(layero).find("iframe")[0].contentWindow.getDept();
				var ids = lui.arrayToString(idArr);
				$.ajax({
					url : "${base}/admin/user/transferDept.do",
					type : "post",
					dataType:'json',
					data : {
						id : lui.arrayToString(idArr),
						depId : dept["id"]
					},
					success : function(text) {
						if(text == "success"){
							lui.info("转移部门成功！");
							lui.close(index);
							reloadGrid({
								org : $("#selectDepId").val()
							});
						}else{
							lui.info(text);
						}
					}
				});
			}
		});
	}

	/**
	 *	树节点点击事件
	 */
	function onClick(event, treeId, treeNode, clickFlag){
		$("#selectDepId").val(treeNode.id);
		var data = {
			org : treeNode.id
		}
		reloadGrid(data); //员工表格刷新
	}

	var zTreeOnAsyncSuccess=function(){

		asyncNodes(zTree.getNodes());
		zTree.expandAll(true);

		//select root node
		var node = zTree.getNodes()[0];
		zTree.selectNode(node);
		zTree.setting.callback.onClick(null, zTree.setting.treeId, node);
	}

	function asyncNodes(nodes) {
		if (!nodes) return;
		var zTree = $.fn.zTree.getZTreeObj("treeDemo");
		for (var i=0, l=nodes.length; i<l; i++) {
			if (nodes[i].isParent && nodes[i].zAsync) {
				asyncNodes(nodes[i].children);
			}
			else {
				zTree.reAsyncChildNodes(nodes[i], "refresh", true);
			}
		}
	}

	function resetPassword(ids) {
		var idArray = new Array();
		for ( var i = 0; i < ids.length; i++) {
			idArray.push(ids[i]);
		}
		$.ajax({
			type : 'POST',
			url : '${ctx}/${frameworkPath}/user/resetpassword',
			traditional : true,
			dataType:'json',
			data : {'usernames' : idArray},
			success : function(data) {
				if(data.success){
					lui.success("重置密码成功")
				}
				else{
					lui.success("重置密码失败")
				}
			},
			error : function(XmlHttpRequest, textStatus, errorThrown) {
				lui.success("重置密码失败")
			}
		});
	};

</script>
